# -*- coding: utf-8 -*-
""" 
@author: xingxingzaixian
@create: 2021/4/26
@description: 所有对数据库的操作
"""
from typing import List, Union, Any

from tortoise.exceptions import DoesNotExist
from tortoise.models import Q

from . import schema
from auth.auth_casbin import get_casbin
from .model import User, RoleCreate, Role, Dept, DeptCreate
from utils.utils import get_password_hash
from utils.response_code import HttpStatus
from fastapi import HTTPException
from tortoise.transactions import atomic, in_transaction


async def get_user_by_name(username: str) -> Union[User, Any]:
    """
    :param username:
    :return:
    """
    try:
        user: User = await User.get(username=username)
    except DoesNotExist as exc:
        raise HTTPException(status_code=HttpStatus.HTTP_421_INNER_PARAM_EXCEPT,
                            detail='用户效验异常，请联系管理员')
        # return None
    return user


async def create_user(user_data: schema.UserCreate) -> User:
    user = User(**user_data.dict(exclude={'confirm'}))
    user.password = get_password_hash(user_data.password)
    await user.save()
    return user


async def create_role(role_data: RoleCreate) -> Role:
    role = Role(**role_data.dict())
    await role.save()
    return role


async def get_role_by_name(role_name: str) -> Union[Role, Any]:
    """
    获取角色信息
    """
    try:
        role: Role = await Role.filter(value=role_name).first()
    except DoesNotExist as exec:
        return None
    return role


async def delete_role_by_name(role_name: str) -> bool:
    """
    删除角色信息，同时删除 casbin 中角色信息
    """
    role: Role = await get_role_by_name(role_name)
    if role:
        role.is_delete = 1
        await role.save()

        # 删除 casbin 的角色权限
        e = await get_casbin()
        e.delete_role(role_name)

        return True
    return False


async def has_role(role_name: str, role_value: str) -> bool:
    """
    判断是否包含角色信息
    """
    role: Role = await Role.filter(Q(name=role_name)|Q(value=role_value)).first()
    # role: Role = await get_role_by_name(role_name)
    if role and not role.is_delete:
        return True
    return False


async def get_user_list() -> List[User]:
    return await User.all()


async def create_dept(dept_data: DeptCreate) -> Role:
    dept = Dept(**dept_data.dict())
    await dept.save()
    return dept


async def get_dept_by_name(dept_name: str) -> Union[Role, Any]:
    """
    获取部门信息
    """
    try:
        dept: Dept = await Dept.get(name=dept_name)
    except DoesNotExist as exec:
        return None
    return dept


async def has_dept(dept_name: str) -> bool:
    '''
    判断是否包含部门信息;
    判断是否重名;
    '''

    dept: Dept = await get_dept_by_name(dept_name)
    if dept and not dept.is_delete:
        return True
    return False


async def delete_dept_by_name(dept_name: str) -> bool:
    """
    删除部门信息，同时删除 casbin 中角色信息
    """
    dept: Dept = await get_role_by_name(dept_name)
    if dept:
        dept.is_delete = 1
        await dept.save()
        return True
    return False
